import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Input, 
  Button, 
  Space, 
  message,
  Modal,
  Form,
  Select,
  Tag
} from 'antd';
import { 
  SearchOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import { UserItem } from '@/types/user';
import { deleteUser, getUsers } from '@/services/userApi';

const { Option } = Select;

const UserList: React.FC = () => {
  const [users, setUsers] = useState<UserItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [deleteUserId, setDeleteUserId] = useState<number | null>(null);

  const { initialState } = useModel('@@initialState');

  // 获取用户列表
  const fetchUsers = async (params = {}) => {
    setLoading(true);
    try {
      const { current = 1, pageSize = 10 } = pagination;
      const searchParams = {
        page: current,
        page_size: pageSize,
        ...params,
      };

      const res = await getUsers(searchParams);
      setUsers(res.results);
      setPagination({
        ...pagination,
        total: res.count,
      });
    } catch (error) {
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [pagination.current, pagination.pageSize]);

  // 搜索
  const handleSearch = (values: any) => {
    fetchUsers(values);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    fetchUsers();
  };

  // 新增用户
  const handleAdd = () => {
    history.push('/user/create');
  };

  // 编辑用户
  const handleEdit = (id: number) => {
    history.push(`/user/edit/${id}`);
  };

  // 查看详情
  const handleView = (id: number) => {
    history.push(`/user/detail/${id}`);
  };

  // 删除用户
  const handleDelete = (id: number) => {
    setDeleteUserId(id);
    setDeleteModalVisible(true);
  };

  // 确认删除
  const confirmDelete = async () => {
    if (deleteUserId === null) return;

    try {
      await deleteUser(deleteUserId);
      message.success('删除成功');
      setDeleteModalVisible(false);
      fetchUsers();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 角色标签
  const renderRoleTag = (role: string) => {
    const roleMap = {
      admin: { color: 'red', text: '管理员' },
      librarian: { color: 'blue', text: '图书管理员' },
      user: { color: 'green', text: '普通用户' },
    };
    const roleInfo = roleMap[role as keyof typeof roleMap] || { color: 'default', text: role };
    return <Tag color={roleInfo.color}>{roleInfo.text}</Tag>;
  };

  // 状态标签
  const renderStatusTag = (isActive: boolean) => {
    return isActive 
      ? <Tag color="green">启用</Tag> 
      : <Tag color="red">禁用</Tag>;
  };

  // 表格列定义
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text: string, record: UserItem) => (
        <a onClick={() => handleView(record.id)}>{text}</a>
      ),
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '姓名',
      dataIndex: 'first_name',
      key: 'first_name',
      render: (_: any, record: UserItem) => `${record.first_name} ${record.last_name}`,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => renderRoleTag(role),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (is_active: boolean) => renderStatusTag(is_active),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: UserItem) => (
        <Space>
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleView(record.id)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record.id)}
          >
            编辑
          </Button>
          {initialState?.currentUser?.id !== record.id && (
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />} 
              onClick={() => handleDelete(record.id)}
            >
              删除
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Form
            form={searchForm}
            layout="inline"
            onFinish={handleSearch}
          >
            <Form.Item name="username" label="用户名">
              <Input placeholder="请输入用户名" style={{ width: 150 }} />
            </Form.Item>
            <Form.Item name="email" label="邮箱">
              <Input placeholder="请输入邮箱" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item name="role" label="角色">
              <Select
                placeholder="请选择角色"
                style={{ width: 150 }}
                allowClear
              >
                <Option value="admin">管理员</Option>
                <Option value="librarian">图书管理员</Option>
                <Option value="user">普通用户</Option>
              </Select>
            </Form.Item>
            <Form.Item name="is_active" label="状态">
              <Select
                placeholder="请选择状态"
                style={{ width: 120 }}
                allowClear
              >
                <Option value="true">启用</Option>
                <Option value="false">禁用</Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>

        <div style={{ marginBottom: 16 }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleAdd}
          >
            添加用户
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination({
                ...pagination,
                current: page,
                pageSize: pageSize,
              });
            },
          }}
        />
      </Card>

      {/* 删除确认模态框 */}
      <Modal
        title="确认删除"
        open={deleteModalVisible}
        onOk={confirmDelete}
        onCancel={() => setDeleteModalVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <p>确定要删除这个用户吗？此操作不可恢复。</p>
      </Modal>
    </div>
  );
};

export default UserList;